
console.log('获取到span的dom如下22')

chrome.runtime.sendMessage({
  from: 'content',
  subject: 'showPageAction',
})

chrome.runtime.onMessage.addListener((msg, sender, response) => {
  // First, validate the message's structure.
  if ((msg.from === 'popup') && (msg.subject === 'DOMInfo')) {
    // Collect the necessary data. 
    // (For your specific requirements `document.querySelectorAll(...)`
    //  should be equivalent to jquery's `$(...)`.)
    var domInfo = '接收到popup消息，这是返回的'

    // Directly respond to the sender (popup), 
    // through the specified callback.
    response(domInfo)
  }
})

/* toast提示 */
function Toast(text) {
  const m = document.createElement('div')
  const toastId = Date.now() + ''
  m.setAttribute('toastId', toastId)
  m.setAttribute('style', 'background: #000;border-radius: 8px;color: #fff;font-size: 28px;left: 50%;max-width: 62.6%;opacity: 0.7;padding: 0 5px;padding: 0.75rem 1rem;position: fixed;text-align: center;top: 20%;transform: translate(-50%, -50%);z-index: 9999999999;');
  m.className = 'Toast'
  m.id = 'jd-toast'
  m.innerHTML = `<div><p>${text}</p><div>`
  document.body.appendChild(m)
  setTimeout(function () {
    const d = 0.5
    m.style.webkitTransition =
      '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in'
    m.style.opacity = '0'
    setTimeout(function () {
      const node1 = document.getElementById('jd-toast')
      if (node1?.getAttribute('toastId') == toastId)
        document.body.removeChild(node1);
    }, d * 1000)
  }, 2000)
}

var intervalID = null

/* =============================================================================================== 
  操作逻辑：
  1.进入批量申报页面。
  2.自动填入预设项。（时段、电量、电价、买卖方向）
  3.按照时段来进行表格行的搜索。找到满足时段的row进行选中。
  4.挂牌电量和挂牌价格列进行自动填充。
  5.触发上方【申报】按钮，进行自动申报
=============================================================================================== */
var mon = String(new Date().getMonth() + 1)
var jianBlock = []
var fengBlock = []
if (['7', '8'].includes(mon)) {
  // 7、8月份
  jianBlock = ['20:00-21:00', '21:00-22:00', '22:00-23:00']
  fengBlock = ['16:00-17:00', '17:00-18:00', '18:00-19:00', '19:00-20:00', '22:00-23:00', '23:00-24:00']
} else {
  // 非7、8月份
  jianBlock = ['18:00-19:00', '19:00-20:00']
  fengBlock = ['16:00-17:00', '17:00-18:00', '20:00-21:00', '21:00-22:00', '22:00-23:00', '23:00-24:00']
}
var pingBlock = ['00:00-01:00', '01:00-02:00', '05:00-06:00', '06:00-07:00', '07:00-08:00', '08:00-09:00', '09:00-10:00', '15:00-16:00']
var guBlock = ['02:00-03:00', '03:00-04:00', '04:00-05:00', '10:00-11:00', '11:00-12:00', '12:00-13:00', '13:00-14:00', '14:00-15:00']

let iframeDom = null
let iframeList = document.getElementsByTagName('iframe')
for (let i = 0; i < iframeList.length; i++) {
  if (iframeList[i].style.display === '') {
    iframeDom = iframeList[i].contentDocument
    break;
  }
}

let tables = iframeDom.getElementsByClassName('el-table__body-wrapper')
var trs = tables[0].querySelectorAll('tr')

var targetTrs = []
function handlerTip(setting) {
  let tables = iframeDom.getElementsByClassName('el-table__body-wrapper')
  trs = tables[0].querySelectorAll('tr')
  
  targetTrs = Array.from(trs).filter(item => {
    let period = item.querySelectorAll('td')[1].querySelector('.el-tag').innerText
    return window[setting.period + 'Block'].includes(period)
  })

  let canBuyTotalArr = targetTrs.map(item => {
    let canBuyTotal = item.querySelectorAll('td')[2].querySelector('.cell').innerText
    return parseFloat(canBuyTotal)
  })

  // canBuyTotalArr.sort((a, b) => {
  //   return a - b
  // })
  // 匹配时段的数据的可买量最小值
  // let minTotal = canBuyTotalArr[0]

  let canBuyTotal = canBuyTotalArr.reduce((accumulator, currentValue) => accumulator + currentValue,
  0)

  chrome.runtime.sendMessage({
    from: 'content',
    type: 'tip',
    msg: canBuyTotal.toFixed(2)
  })
}


function runHandler(setting) {
  const trsLen = trs.length
  Array.from(trs).forEach((item, index) => {
    let period = item.querySelectorAll('td')[1].querySelector('.el-tag').innerText
    
    if (window[setting.period + 'Block'].includes(period)) {
      item.querySelectorAll('td')[0].querySelector('.el-checkbox__original').checked = true

      let directionArr = item.querySelectorAll('td')[5].querySelectorAll('.el-radio__label')
      Array.from(directionArr).forEach(ele => {
        if (ele.innerText === setting.type) {
          ele.click()
        }
      })

      
      if (index < trsLen - 1) {
        item.querySelectorAll('td')[6].querySelector('input').value = (setting.total / targetTrs.length).toFixed(3)
      } else {
        item.querySelectorAll('td')[6].querySelector('input').value = (parseFloat(setting.total) - parseFloat((setting.total / targetTrs.length).toFixed(3)) * (targetTrs.length - 1)).toFixed(3)
      }
      item.querySelectorAll('td')[7].querySelector('input').value = setting.price

    }
  })
  let btns = iframeDom.getElementsByClassName('el-button')
  let btn = Array.from(btns).filter(item => {
    return item.lastElementChild.innerText === '申 报'
  })
  btn[0].click()
}

function stopExecute() {

}
// function compareTime(setting) {
//   /* 寻找提交按钮dom */
//   let iframeDom = null
//   let iframeList = document.getElementsByTagName('iframe')
//   for (let i = 0; i < iframeList.length; i++) {
//     if (iframeList[i].style.display === '') {
//       iframeDom = iframeList[i].contentDocument
//       break;
//     }
//   }

//   if (!iframeDom) {
//     Toast('未找到[申 报]按钮')
//     return
//   }

//   let btnObjs = iframeDom.getElementsByClassName('el-button')

//   let targetBtn = Array.from(btnObjs).filter(item => {
//     if (item.lastElementChild.innerHTML === '申 报') {
//       return item.lastElementChild
//     }
//   })

//   if (!targetBtn[0]) {
//     console.log('未找到[申 报]按钮')
//     Toast('未找到[申 报]按钮')
//     return
//   }

//   /* 寻找时钟dom */
//   let timeDom = document.getElementsByClassName('header-time-bar')
//   if (!timeDom) {
//     Toast('未找到[时钟]内容')
//     return
//   } else {
//     let i = 0
//     intervalID = setInterval(() => {
//       i = ++i
//       let t = timeDom[0].firstChild.innerHTML
//       let hms = t.split(' ')[1]
//       let hour = hms.slice(0, 2)
//       let min = hms.slice(3, 5)
//       let sec = hms.slice(6, 8)
//       console.log('执行第' + i + '次')
//       // log.appendChild('<span>执行第' + i + '次</span>')
//       chrome.runtime.sendMessage({
//         from: 'content',
//         index: i,
//       })
//       if (setting.hour === hour && setting.min === min && setting.sec === sec) {
//         targetBtn[0].click()
//         clearInterval(intervalID)
//         console.log('执行完成')
//         // log.appendChild('<span style="color: red">执行完成</span>')
//         chrome.runtime.sendMessage({
//           from: 'content',
//           index: 0,
//         })
//         Toast('执行')
//       }
//     }, 10) // 执行频率
//   }
// }

